<?php

namespace Admin\Controller;
use Common\Controller\BackendController;

class LoginController extends BackendController {
    /**
     * 第三方帐号登陆和绑定
     */
    public function index() {
    	$mod = $this->_get('mod', 'trim');

    	!$mod && $this->_404();
		$referer = $_SERVER['HTTP_REFERER'];
		cookie('referer', $referer);

        import("ITK.Itklib.oauth");
        $oauth = new \oauth($mod);
        $redirectUrl=C('itk_site_url').'index.php?m=admin&c=login&a=callback&mod=taobao';
        $oauth->setRedirectUrl($redirectUrl);
        return $oauth->authorize();
    }

    /**
     * 登陆回调页面
     */
    function callback() {
        $mod = $this->_get('mod', 'trim');
        !$mod && $this->_404();
        $callback_type = cookie('callback_type');
        import("ITK.Itklib.oauth");
        $oauth = new \oauth($mod);
        $rk = $oauth->NeedRequest();
		
        $request_args = array();
        foreach ($rk as $v) {
            $request_args[$v] = $this->_get($v);
        }

        $user = $oauth->getUserSession($request_args);
        // 放入seesionKey
        $key='user_session';
        $val = $user['bind_info']['access_token'];
        $res = D('Setting')->where(array('name' => $key))->select();
        if(!$res){
            $datas['name'] = $key;
            $datas['data'] = $val;
            D('Setting')->add($datas);
            //记录时间
            $datas['name'] = 'session_time';
            $datas['data'] = time();
            D('Setting')->add($datas);
        }else{
            $res = D('Setting')->where(array('name' => $key))->save(array('data' => $val));
            $res = D('Setting')->where(array('name' => 'session_time'))->save(array('data' => time()));
        }
        $url=U('Privilege/index');
        redirect($url);
    }
    
    
    public function itaoke(){
        $urls = 'http://i.itaoke.org/Oauth?do=taoyohui&view='.$_SERVER['SERVER_NAME'];
        header("Location:".$urls);
    }
    
    public function loginCallback(){
        $token=I('token');
        if(!$token){ //获取失败
            $this->error('获取sessionKey失败',U('Privilege/index'));
        }else{
            // 记录token
            $key='user_session';
            $val = $token;
            $res = D('Setting')->where(array('name' => $key))->select();
            if(!$res){
                $datas['name'] = $key;
                $datas['data'] = $val;
                D('Setting')->add($datas);
                //记录时间
                $datas['name'] = 'session_time';
                $datas['data'] = time();
                D('Setting')->add($datas);
            }else{
                $res = D('Setting')->where(array('name' => $key))->save(array('data' => $val));
                $res = D('Setting')->where(array('name' => 'session_time'))->save(array('data' => time()));
            }
            $url=U('Privilege/index');
            redirect($url);
        }
    }
    
}